package com.kgc.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUtil {
    /**
     * 删除文件
     * @param path   文件相对路径
     * @param rootPath 服务器应用根路径
     */
    public static void deleteFile(String path,String rootPath){
        if(path != null && !"".equals(path)){
            String absPhotoPath = rootPath + path;
            File file = new File(absPhotoPath);
            if(file.exists()){
                //删除文件
                file.delete();
            }
        }
    }


    public static String uploadFile(ServletContext application, MultipartFile photoFile){
        //获取发布项目的跟路径
        String rootPath = application.getRealPath("/");
        System.out.println(rootPath);
        //创建文件夹
        String dirName = "uploadImg";
        String dirPath = rootPath + dirName;
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        //获取文件名
        String fileName = photoFile.getOriginalFilename();
        //更名
        String uuid = UUIDUtil.createUUID();
        String newName = uuid + fileName.substring(fileName.lastIndexOf("."));
        File file = new File(dirPath + File.separator + newName);

        try {
            //一行代码搞定文件上传
            photoFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dirName + File.separator + newName;
    }

}
